SRCROOT=.

CPP    = g++  
CC     = gcc
AR     = ar -rc

CPPSHARE = $(CPP) -fPIC -shared -O2 -pipe -o
CSHARE   = $(CC) -fPIC -shared -O2 -pipe -o

ifeq ($v,release)
CFLAGS = -c -O2 $(INCLS) -fPIC -DLINUX -pipe
else
CFLAGS = -c -g $(INCLS) -fPIC -DLINUX -pipe
endif

CPPCOMPI = $(CPP) $(CFLAGS) 
CCCOMPI  = $(CC) $(CFLAGS) 

STATICLIBPATH  = $(SRCROOT)/lib
DYNAMICLIBPATH = $(SRCROOT)/solib

INCLS = -I$(SRCROOT)/include
LIBS  = -L$(STATICLIBPATH)
LIBS  += -lpthread

OBJS  = lsg_utils.o lsg_log.o lsg_buddybit.o lsg_buddyfile.o lsg_filebucket.o
PROGS = liblightstorage.a liblightstorage.so
TEST  = test_buddybit test_buddyfile test_hashfile test_filebucket test_log

all: $(PROGS)
test: $(TEST)

liblightstorage.a: $(OBJS)
	@( \
		echo -n "archieving $@ ..."; \
		$(AR) $(STATICLIBPATH)/$@ $+; \
		if [ $$? -ne 0 ]; then \
		exit 1; \
		else \
		echo "OK"; \
		fi \
	 )

liblightstorage.so: $(OBJS) 
	@( \
		echo -n "archieving $@ ..."; \
		$(CPPSHARE) $(DYNAMICLIBPATH)/$@ $+; \
		if [ $$? -ne 0 ]; then \
		exit 1; \
		else \
		echo "OK"; \
		fi \
	 )

test_buddybit: lsg_utils.o lsg_log.o lsg_buddybit.o test_buddybit.o
	$(CPP) -o $@ $+

test_buddyfile: lsg_utils.o lsg_log.o lsg_buddybit.o lsg_buddyfile.o test_buddyfile.o
	$(CPP) -o $@ $+

test_hashfile: lsg_utils.o lsg_log.o test_hashfile.o
	$(CPP) -o $@ $+

test_filebucket: lsg_utils.o lsg_log.o lsg_buddybit.o lsg_buddyfile.o lsg_filebucket.o test_filebucket.o
	$(CPP) -o $@ $+

test_log: lsg_log.o test_log.o
	$(CPP) -o $@ $+

clean:
	rm -f *.o $(PROGS) $(TEST) $(STATICLIBPATH)/*.a $(DYNAMICLIBPATH)/*.so 

##define the cpp file compile rule
.cpp.o:
	@( \
		echo -n "compiling $< ... "; \
		$(CPPCOMPI)  $< 2>./.err.txt; \
		if [ $$? -ne 0 ];then \
		echo "Failed"; \
		cat ./.err.txt; \
		rm -f ./.err.txt; \
		exit 1; \
		else \
		rm -f ./.err.txt; \
		echo "OK"; \
		fi \
	 )

.c.o:
	@( \
		echo -n "compiling $< ... "; \
		$(CCCOMPI)  $< 2>./.err.txt; \
		if [ $$? -ne 0 ];then \
		echo "Failed"; \
		cat ./.err.txt; \
		rm -f ./.err.txt; \
		exit 1; \
		else \
		rm -f ./.err.txt; \
		echo "OK"; \
		fi \
	 )
